<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules" class="mr20" label-width="120px" style="width: 100%;">
      <!-- 基本信息 -->
      <el-divider content-position="left"><span class="divider-title">▶基本信息◀</span></el-divider>
      <el-row :gutter="20" class="extra-margin">
        <el-col :span="6">
          <el-form-item label="患者姓名" prop="name">
            <span class="name-css">{{ form.name }}</span><span
              v-if="form.newbornFlag === 'Y'">(新生儿)</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择性别" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['sys_user_sex']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="form.newbornFlag === 'N'" label="职业" prop="occupation">
            <el-select v-model="form.occupation" placeholder="请选择职业" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['profession_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <el-form-item v-else label="出生日期" prop="birthdayDate">
            <el-date-picker v-model="form.birthdayDate" type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择生日" :disabled="!isEdit">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-row>
            <el-col :span="8" style="margin-right: -40px;">
              <el-form-item label="年龄" prop="age">
                <el-input v-model="form.age" placeholder="岁" class="age" ref="ageRef"
                          :disabled="!isEdit">
                  <template #append>岁</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-right: -40px;">
              <el-form-item prop="ageMonth">
                <el-input v-model="form.ageMonth" placeholder="月" class="age"
                          :disabled="!isEdit">
                  <template #append>月</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" style="margin-right: -40px;">
              <el-form-item prop="ageDay">
                <el-input v-model="form.ageDay" placeholder="天" class="age"
                          :disabled="!isEdit">
                  <template #append>天</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="身份证号" prop="idNo">
            <el-input v-model="form.idNo" placeholder="请输入身份证号" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="国籍" prop="nationality">
            <el-select v-model="form.nationality" placeholder="请选择国籍" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['nationality_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="民族" prop="nation">
            <el-select v-model="form.nation" placeholder="请选择民族" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['nation_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="form.newbornFlag === 'N'">
          <el-form-item label="工作单位" prop="workContract" >
            <el-input v-model="form.workContract" placeholder="请输入工作单位" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <template v-else>
          <el-col :span="6">
            <el-row>
              <el-col :span="8" class="age-margin">
                <el-form-item prop="ageHours" label="出生时刻">
                  <el-input v-model="form.ageHours" placeholder="时" class="age"
                            :disabled="!isEdit">
                    <template #append>时</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="1" class="age-margin">
                <el-form-item prop="ageMinutes">
                  <el-input v-model="form.ageMinutes" placeholder="分" class="age"
                            :disabled="!isEdit">
                    <template #append>分</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </template>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮编" prop="zipCode">
            <el-input v-model="form.zipCode" placeholder="请输入邮编" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文化程度" prop="eduLevel">
            <el-select v-model="form.eduLevel" placeholder="请选择文化程度" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['education_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="婚姻" prop="marriage">
            <el-select v-model="form.marriage" placeholder="请选择婚姻" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['marriage_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="籍贯" prop="nativePlace">
            <level-address :value="form.nativePlaceCode" @handleChange="handleChangeNativePlaceCode"
                           style="width: 50%;" :disabled="!isEdit"/>
            <el-input v-model="form.nativePlace" auto-complete="" placeholder="请输入籍贯"
                      style="width: 50%;" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生地" prop="homePlace">
            <level-address :value="form.homePlaceCode" @handleChange="handleChangeHomePlaceCode"
                           style="width: 50%;" :disabled="!isEdit"/>
            <el-input v-model="form.homePlace" auto-complete="" placeholder="请输入出生地"
                      style="width: 50%;" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="住址" prop="address">
            <level-address :value="form.addressCode" @handleChange="handleChangeAddressCode"
                           style="width: 50%;" :disabled="!isEdit"/>
            <el-input v-model="form.address" placeholder="请输入住址"
                      style="width: 50%;" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 入院信息 -->
      <el-divider content-position="left"><span class="divider-title">▶入院信息◀</span></el-divider>
      <el-row :gutter="20"  class="extra-margin">
        <el-col :span="6">
          <el-form-item label="入院时间" prop="admissionTime">
            <el-date-picker v-model="form.admissionTime" type="datetime" placeholder="请选择入院时间" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院科室" prop="deptAdmissionTo">
            <dept-list style="width: 100%" :clinic-vs-visit-str="'1,2'" v-model="form.deptAdmissionTo"
                       :dept-id="form.deptAdmissionTo" :disabled="!isEdit" :org-id="userInfo.orgId"
                       :placeholder="'请选择入院科室'"
                       @deptChange="deptChange"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院病区" prop="wardAdmissionTo">
            <dept-vs-bed-list style="width: 100%" :clinical-sign-str="'3'"
                              v-model="form.wardAdmissionToName"
                              :disabled="!isEdit"
                              :dept-id="form.wardAdmissionTo" :org-id="userInfo.orgId"
                              :placeholder="'请选择入院病区'"
                              @deptChange="wordChange"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院情况" prop="hospitalSituation">
            <el-select v-model="form.hospitalSituation" placeholder="请选择入院情况" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['admission_situation_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="费别" prop="chargeType">
            <el-select v-model="form.chargeType" placeholder="请选择费别" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['medical_insurance_type']" :key="dict.dictValue"
                         :label="dict.dictLabel"
                         :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院途径" prop="channel">
            <el-select v-model="form.channel" placeholder="请选择入院途径" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['patient_class_dict']" :key="dict.dictValue"
                         :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人地址" prop="contactsAddress">
            <level-address :value="form.contactsAddressCode" @handleChange="handleChangeContactsAddressCode"
                           style="width: 50%;" :disabled="!isEdit"/>
            <el-input v-model="form.contactsAddress" auto-complete="" placeholder="请输入联系人地址"
                      style="width: 50%;" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="隔离情况" prop="quarantine">
            <el-radio-group v-model="form.quarantine" :disabled="!isEdit">
              <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                        :value="dict.dictValue">{{
                  dict.dictLabel
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人电话" prop="contactsPhone">
            <el-input v-model="form.contactsPhone" placeholder="请输入联系人电话" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人关系" prop="contactsRelation">
            <el-select v-model="form.contactsRelation" placeholder="请选择联系人关系" :disabled="!isEdit">
              <el-option v-for="dict in dictDataMap['relationship_dict']" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人身份证号" prop="contactsIdNo">
            <el-input v-model="form.contactsIdNo" placeholder="请输入联系人身份证号" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 其他信息 -->
      <el-divider content-position="left"><span class="divider-title">▶其他信息◀</span></el-divider>
      <el-row :gutter="20"  class="extra-margin">
        <el-col :span="12">
          <el-form-item label="门诊诊断" prop="clinicDiagnosis">
            <el-input v-model="form.clinicDiagnosis" type="textarea" :rows="2" placeholder="请输入门诊诊断" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建议预交金" prop="paymentAdvice">
            <el-input v-model.number="form.paymentAdvice" placeholder="请输入建议预交金" :disabled="!isEdit">
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="注意事项" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="2" placeholder="请输入注意事项" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm" :disabled="!form.clinicDiagnosis" style="float: right;" v-if="isEdit">
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
export default {
  name: "PatVisitIndex"
}
</script>

<script setup lang="ts">
import {
  getHosPatientInfo, addHospitalizationNotice, delHospitalizationNotice,
  getHospitalizationNotice, listHospitalizationNotice, updateHospitalizationNotice
} from "@/api/hospitalization/HospitalizationNotice.ts";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {idNo, phone} from "@/utils/myRules";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('profession_dict', 'medical_insurance_type', 'nationality_dict', 'relationship_dict',
    'medical_insurance_type', 'sys_yes_no', 'sys_user_sex', 'nation_dict', 'pay_way_dict', 'marriage_dict', 'education_dict',
    'admission_situation_dict', 'patient_class_dict'))

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const clinicId = ref(proxy.$clinicId)
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

/**
 * 页面元素是否能够编辑
 */
const isEdit = ref<boolean>(true)

const props = defineProps({
  inoroutFlag: {
    type: String,
    default: "",
  },
  orgId: {
    type: String,
    default: "",
  },
});

const formRef = ref();
const open = ref(false);
const form = ref<any>({
  visitIndexId: "",
  visitId: "",
  newbornFlag: "Y",
  name: "",
  inputCode: "",
  height: "",
  weight: 0,
  sex: "",
  marriage: "",
  occupation: "",
  age: 0,
  ageMonth: 0,
  ageDay: 0,
  ageHours: 0,
  ageMinutes: 0,
  nation: "",
  nationality: "",
  canBaoType: "",
  birthdayDate: "",
  nativePlace: "",
  nativePlaceCode: "",
  zipCode: "",
  homePlaceCode: "",
  homePlace: "",
  addressCode: "",
  address: "",
  identity: "",
  idNo: "",
  phone: "",
  contacts: "",
  contactsAddress: "",
  contactsAddressCode: "",
  contactsPhone: "",
  contactsRelation: "",
  unitInContractId: "",
  unitInContract: "",
  workContract: "",
  affiliatingArea: "",
  insuranceType: "",
  isCard: "",
  insuranceNo: "",
  chargeType: "",
  externalCause: "",
  autopsyFlag: "",
  practiceDoctor: "",
  engageDoctor: "",
  isDrugAllerge: "",
  drugAllergy: "",
  orgId: "",
  remarks: "",
  rh: "",
  abo: "",
  pathologicalDiagCode: "",
  pathologicalNo: "",
  pathologicalDiag: "",
  registZipCode: "",
  registAddress: "",
  registAddressCode: "",
  workCode: "",
  workPhone: "",
  externalCauseCode: "",
  paymentAdvice: 0,
  residenceNo: "",
  medicalPayWay: "",
  brainDamageTimeBeforeDay: "",
  brainDamageTimeBeforeHour: "",
  brainDamageTimeBeforeMinute: "",
  brainDamageTimeAfterDay: "",
  brainDamageTimeAfterHour: "",
  brainDamageTimeAfterMinute: "",
  comeAgainIf: "",
  comeAgainPurpose: "",
  persType: "",
  centerId: "",
  eduLevel: "",
  matnType: "",
  latechbFlag: "",
  pretFlag: "",
  birctrlMatnDate: "",
  fpscNo: "",
  birctrlType: "",
  gesoVal: "",
  fetts: "",
  fetusCnt: "",
  localFlag: "",
  admissionTime: new Date(),
  deptAdmissionTo: "",
  wardAdmissionTo: "",
  hospitalSituation: "",
  channel: "1",
  contactsIdNo: "",
  quarantine: "N",
  clinicDiagnosis: ""
})

const rules = ref({
  visitIndexId: [
    {
      required: true, message: "主键不能为空", trigger: "blur"
    }
  ],
  name: [
    {
      required: true, message: "患者姓名不能为空", trigger: "blur"
    }
  ],
  sex: [
    {
      required: true, message: "性别不能为空", trigger: "change"
    }
  ],
  nativePlace: [
    {
      required: true, message: "籍贯不能为空", trigger: "blur"
    }
  ],
  paymentAdvice: [
    {
      required: true, message: "建议预交金不能为空", trigger: "blur"
    }
  ],
  admissionTime: [
    {
      required: true, message: "入院时间不能为空", trigger: "change"
    }
  ],
  idNo: [{required: true, validator: idNo, trigger: "blur"}],
  phone: [{required: true, message: "电话不能为空", trigger: "blur"}],
  contactsPhone: [{required: true, message: "电话不能为空", trigger: "blur"}],
  contacts: [
    {
      required: true, message: "联系人不能为空", trigger: "blur"
    }
  ],
  deptAdmissionTo: [
    {
      required: true, message: "入院科室不能为空", trigger: "change"
    }
  ],
  wardAdmissionTo: [
    {
      required: true, message: "入院病区不能为空", trigger: "change"
    }
  ],
})


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    visitIndexId: "",
    visitId: "",
    newbornFlag: "0",
    name: "",
    inputCode: "",
    height: "",
    weight: 0,
    sex: "",
    marriage: "",
    occupation: "",
    age: 0,
    ageMonth: 0,
    ageDay: 0,
    ageHours: 0,
    ageMinutes: 0,
    nation: "",
    nationality: "",
    canBaoType: "",
    birthdayDate: "",
    nativePlace: "",
    nativePlaceCode: "",
    zipCode: "",
    homePlaceCode: "",
    homePlace: "",
    addressCode: "",
    address: "",
    identity: "",
    idNo: "",
    phone: "",
    contacts: "",
    contactsAddress: "",
    contactsAddressCode: "",
    contactsPhone: "",
    contactsRelation: "",
    unitInContractId: "",
    unitInContract: "",
    workContract: "",
    affiliatingArea: "",
    insuranceType: "",
    isCard: "",
    insuranceNo: "",
    chargeType: "",
    externalCause: "",
    autopsyFlag: "",
    practiceDoctor: "",
    engageDoctor: "",
    isDrugAllerge: "",
    drugAllergy: "",
    orgId: "",
    remarks: "",
    rh: "",
    abo: "",
    pathologicalDiagCode: "",
    pathologicalNo: "",
    pathologicalDiag: "",
    registZipCode: "",
    registAddress: "",
    registAddressCode: "",
    workCode: "",
    workPhone: "",
    externalCauseCode: "",
    paymentAdvice: 0,
    residenceNo: "",
    medicalPayWay: "",
    brainDamageTimeBeforeDay: "",
    brainDamageTimeBeforeHour: "",
    brainDamageTimeBeforeMinute: "",
    brainDamageTimeAfterDay: "",
    brainDamageTimeAfterHour: "",
    brainDamageTimeAfterMinute: "",
    comeAgainIf: "0",
    comeAgainPurpose: "",
    persType: "",
    centerId: "",
    eduLevel: "",
    matnType: "",
    latechbFlag: "",
    pretFlag: "",
    birctrlMatnDate: "",
    fpscNo: "",
    birctrlType: "",
    gesoVal: "",
    fetts: "",
    fetusCnt: "",
    localFlag: "",
    channel: "1",
  };
  nextTick(() => {
    formRef.value.resetFields()
  })
}

function handleChangeNativePlaceCode(obj: any) {
  if (obj) {
    form.value.nativePlaceCode = obj['townlet'].value
    form.value.nativePlace = initAddrStr(obj)
  }
}
function handleChangeHomePlaceCode(obj: any) {
  if (obj) {
    form.value.homePlaceCode = obj['townlet'].value
    form.value.homePlace = initAddrStr(obj)
  }
}
function handleChangeAddressCode(obj: any) {
  if (obj) {
    form.value.addressCode = obj['townlet'].value
    form.value.address = initAddrStr(obj)
  }
}
function handleChangeContactsAddressCode(obj: any) {
  if (obj) {
    form.value.contactsAddressCode = obj['townlet'].value
    form.value.contactsAddress = initAddrStr(obj)
  }
}

function initAddrStr(obj: any) {
  return obj['economize'].label + obj['city'].label + obj['county'].label + obj['townlet'].label + form.value.address
}

function getList() {
  const param = {
    clinicId: clinicId.value
  }
  getHosPatientInfo(param).then((res: resType) => {
    form.value = res.data
    // 设置页面元素能否编辑
    isEdit.value = form.value.inFlag == null;
    if (!form.value.clinicDiagnosis) {
      ElMessage.error("患者没有门诊诊断，不能开具住院申请单");
    }
    if (!form.value.quarantine) {
      form.value.quarantine = "N"
    }
    if (!form.value.hospitalSituation) {
      form.value.hospitalSituation = "1"
    }
    if (!form.value.channel) {
      form.value.channel = "1"
    }
    if (!form.value.eduLevel) {
      form.value.eduLevel = "10"
    }
  })
}

/** 重置按钮操作 */
function resetQuery() {

}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      ElMessageBox.confirm('确认要开具住院申请单吗？',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        form.value.admissionTime = proxy.$parseTime(form.value.admissionTime, "{y}-{m}-{d} {h}:{i}:{s}")
        if (form.value.noticeId != null) {
          updateHospitalizationNotice(form.value).then((response: any) => {
            ElMessage.success("住院申请修改成功");
            getList();
          }).finally(() => {
          });
        } else {
          addHospitalizationNotice(form.value).then((response: any) => {
            ElMessage.success("住院申请开具成功");
            getList();
          }).finally(() => {
          });
        }

      }).catch(() => {
      })
    }
  });
}

function wordChange(obj) {
  form.value.wardAdmissionTo = obj.wardCode
  form.value.deptAdmissionToName = obj.wardCodeName
}

function deptChange(obj) {
  form.value.deptAdmissionTo = obj.deptId
}

getList();
</script>

<style scoped>:deep(.age .el-input__inner) {
  width: 40px;
}

.search-container {
  padding: 18px 0 30px 10px;
}

:deep(.el-input-group__append) {
  padding: 0 5px;
  width: 40px;
}

.name-css {
  font-size: 14px;
  color: rgb(51, 91, 249);
  margin-right: 10px;
}

/* 增加表单项之间的垂直间距 */
.divider-title {
  color: rgb(6, 138, 194);
  font-weight: bold;
  font-size: 14px;
}

/* 增加表单项之间的垂直间距 */
.el-form-item {
  margin-bottom: 16px;
}

/* 调整标签和输入框的对齐方式 */
.el-form-item__label {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
}
.extra-margin {
  margin-top: 30px; /* 根据需要调整具体的值 */
}
/* 统一输入框的宽度 */
.el-input, .el-select, .el-textarea {
  width: 100%;
}
</style>
